package com.henry.encryptor;

import com.henry.constants.EncryptConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * AES 对称加密工具类
 *
 * @author Liu Hanlin
 * @create 2025-08-16 11:25
 */
@Component(EncryptConstants.AES)
public class AesEncryptor implements Encryptor {

    @Override
    public String encrypt(String plainText, String secretKey) throws Exception {

        if (StringUtils.isAnyEmpty(plainText, secretKey)) {
            throw new RuntimeException("待加密数据和密钥不能为null");
        }
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(plainText.getBytes());
        // 返回加密后的数据（Base64 编码）
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    @Override
    public String decrypt(String cipherText, String secretKey) throws Exception {

        if (StringUtils.isAnyEmpty(cipherText, secretKey)) {
            throw new RuntimeException("待解密数据和密钥不能为null");
        }
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        // 返回解密后的字符串
        return new String(decryptedData);
    }
}
